package com.example.fw;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;

public class DataBaseHelper extends HelperBase{

	private Connection conn;
	
	public DataBaseHelper(ApplicationManager manager) {
		super(manager);
		try {
			// sozdanie novogo obekta tipa "com.mysql.jdbc.Driver",initcializatciya bd
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			// ustanovlenie coedineniya
			conn = DriverManager.getConnection(manager.getProperty("db.url"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public Set<GroupObject> getGroups() {
		Set<GroupObject> groups = new HashSet<GroupObject>();
		// cozdaem obect-sam zapros
		Statement st = null;
		//ozdaem obect - suda pomestitsya rezultat vypolneniya zaprosa
		ResultSet res = null;
		
		try {
			//initcializatcya obecta
			st = conn.createStatement();
			res = st.executeQuery("SELECT group_id,group_name,group_header,group_footer FROM group_list");
			//poka stroka ne kon4itsya
			while (res.next()) {				
				groups.add(new GroupObject()
						.setId(res.getString(1))
						.setName(res.getString(2))
						.setHeader(res.getString(3))
						.setFooter(res.getString(4)));
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} //sdelat obyazatelno, ne zavisimo ot vypolneniya b nevypolnenya usloviya veshe
		  finally {
			try {
				res.close();
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return groups;
	}
	
	public String getLastGroupsId() {
		// cozdaem obect-sam zapros
		Statement st = null;
		//ozdaem obect - suda pomestitsya rezultat vypolneniya zaprosa
		ResultSet res = null;
		
		try {
			//initcializatcya obecta
			st = conn.createStatement();
			res = st.executeQuery("SELECT MAX(group_id)FROM group_list");
			//poka stroka ne kon4itsya
			if (res.next()) {	
				return res.getString(1);							
			} else {
				return null;
			}
		} // obrabotka vozmoznyh problem
		  catch (SQLException e) {
			e.printStackTrace();
			return null;
		} //sdelat obyazatelno, ne zavisimo ot vypolneniya b nevypolnenya usloviya veshe
		  finally {
			try {
				res.close();
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
